package query;

import sort.BubbleSort;

/**
 * @author:李雄
 * @ClassName:BinarySearch
 * @Description:二分查找算法,返回第一个目标值的下标
 * @createTime:2022-11-13 20:54
 */
public class BinarySearch {

    public static void main(String[] args) {
        int arr[] = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
        int index = myBinarySearch(arr, 6, 0, arr.length - 1);
        System.out.println(index);
    }

    public static int myBinarySearch(int arr[], int target, int start, int end) {
        int mid = (start + end) / 2;
        int index = mid;
        System.out.println("中间值：" + mid);
        if (arr[mid] == target) {
            return index;
        }
        if (arr == null || arr.length == 0) {
            System.out.println("此数组中无查询值");
            return 0;
        }
        if (start == end && arr[mid] != target) {
            System.out.println("此数组中无查询值");
            return 0;
        }
        if (arr[mid] != target) {
            if (arr[mid] < target) {
                index = myBinarySearch(arr, target, mid + 1, end);
            }
            if (arr[mid] > target) {
                index = myBinarySearch(arr, target, start, mid - 1);
            }
        }
        return index;
    }

}
